package cn.xinfei.xdecision.data.core.frame.retry;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class CustomLogInterceptor implements Interceptor {

    private final Logger LOGGER = LoggerFactory.getLogger(CustomLogInterceptor.class);

    private final static Integer BYTE_CNT = 1024;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();//收到响应的时间

        long duration = endTime - startTime;

        String requestString = "";
        RequestBody requestBody = request.body();
        Headers headers = request.headers();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            requestString = buffer.readUtf8();
        }

        ResponseBody responseBody = response.peekBody(BYTE_CNT * BYTE_CNT);
        if (response.isSuccessful()) {
            LOGGER.info("[--> {} {} {} ({})]", request.method(), response.code(), request.url(), duration);
            LOGGER.info("[--> body: {}]", requestString);
            LOGGER.info("[--> headers: {}]", JSONObject.toJSONString(headers.toString()));
            LOGGER.info("[<-- resp: {}]\n", responseBody.string());
        } else {
            LOGGER.error("[--> {} {} {} ({})]", request.method(), response.code(), request.url(), duration);
            LOGGER.error("[--> body: {}]", requestString);
            LOGGER.info("[--> headers: {}]", JSONObject.toJSONString(headers.toString()));
            LOGGER.error("[<-- resp: {}]\n", responseBody.string());
        }
        return response;
    }


}
